import type { Env } from '../../types';
import { saveShareFile, getShareFileList } from '../fileApi';
import { createErrorResponse } from '../../utils/errorHandler';

export async function handleFileApiRequest(
  request: Request,
  url: URL,
  env: Env
): Promise<Response> {
  const path = url.pathname;
  const method = request.method;

  switch (method) {
    case 'GET':
      // 获取文件列表
      if (path === '/api/file/list') {
        return await getList(request, url, env);
      } else if (path.startsWith('/api/file/get')) {
        return await getFile(request, url, env);
      }
      break;
    case 'POST':
      if (path === '/api/file/upload') {
        return await postFile(request, url, env);
      }
      break;
    case 'DELETE':
      if (path === '/api/file/upload') {
        return await deleteFile(request, url, env);
      }
      break;
    default:
  }
  return createErrorResponse('Not found', 404);
}


/**
 * 获取文件
 * @param req 
 * @param url 
 * @param env 
 * @returns 
 */
async function getList(req: Request, url: URL, env: Env): Promise<Response> {
  const result = await getShareFileList(env);
  if (!result.success) {
    return createErrorResponse(result.error || 'Failed to get file list', 500);
  }
  return new Response(JSON.stringify(result.data), { headers: { 'content-type': 'application/json' } });

}


/**
 * 上传文件

 * @param req 
 * @param url 
 * @param env 
 * @returns 
 */
async function postFile(req: Request, url: URL, env: Env): Promise<Response> {
  try {
    const formData = await req.formData();
    const file = formData.get('file') as File | null;
    const description = formData.get('description') as string | null;
    const userId = parseInt(formData.get('userId') as string || '1');
    const groupId = parseInt(formData.get('groupId') as string || '1');
    const fingerprintId = req.headers.get('fingerprint') as string || 'unknown';

    if (!file) {
      return createErrorResponse('File is required', 400);
    }

    // 文件处理逻辑
    const result = await saveShareFile(env, file, description || '', userId, groupId, fingerprintId);
    if (!result.success) {
      return createErrorResponse(result.error || 'Failed to upload file', 500);
    }

    return new Response(JSON.stringify(result.data), { headers: { 'content-type': 'application/json' }, status: 201 });
  } catch (error) {
    console.error('Error uploading file:', error);
    return createErrorResponse('Invalid request', 400);
  }
}


/**
 * 获取文件
 * @param req 
 * @param url 
 * @param env 
 * @returns 
 */
async function getFile(req: Request, url: URL, env: Env): Promise<Response> {
  try {
    const formData = await req.formData();
    const file = formData.get('file') as File | null;
    const description = formData.get('description') as string | null;
    const userId = parseInt(formData.get('userId') as string || '1');
    const groupId = parseInt(formData.get('groupId') as string || '1');
    const fingerprintId =  req.headers.get('fingerprint') as string || 'unknown';

    // if (!file) {
    //   return createErrorResponse('File is required', 400);
    // }

    // // 文件处理逻辑
    // const result = await saveShareFile(env, file, description || '', userId, groupId, fingerprintId);
    // if (!result.success) {
    //   return createErrorResponse(result.error || 'Failed to upload file', 500);
    // }

    return new Response('Get file', { status: 200 });

  } catch (error) {
    console.error('Error uploading file:', error);
    return createErrorResponse('Invalid request', 400);
  }
}


async function deleteFile(req: Request, url: URL, env: Env): Promise<Response> {
  return new Response('Delete file', { status: 200 });
}
